package com.java.zhuiyun.api.back_course.contoller;

import com.java.zhuiyun.api.back_course.entity.BackCourse;
import com.java.zhuiyun.api.back_course.model.BackCourseModel;
import com.java.zhuiyun.api.back_course.service.BackCourseService;
import com.java.zhuiyun.api.course_unit.entity.CourseUnit;
import com.java.zhuiyun.api.dict_navigation_tabs.entity.SysDictPc;
import com.java.zhuiyun.common.response.CommonResult;
import com.java.zhuiyun.util.pageUtil.PageRequest;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName BackCourseController
 * @Description TODO
 * @Author 杨友朋
 * @Date 2023/8/14 15:18
 **/
@RestController
@CrossOrigin
@RequestMapping("/back_course")
public class BackCourseController {
    @Resource
    BackCourseService backCourseService;

    /**
    * @Author 杨友朋
    * @Description TODO 查询课程
    * @Date 2023/8/14 16:42
    * @Return
    * @param backCourse,pageRequest
    */
    @GetMapping("/selectCourse")
    public CommonResult selectCourse(BackCourseModel backCourse, PageRequest pageRequest){
        return CommonResult.ok(backCourseService.selectCourse(backCourse,pageRequest));
    }

    @GetMapping("/selectTeacherId")
    public CommonResult selectTeacherId(Integer userId){
        return CommonResult.ok(backCourseService.selectTeacherId(userId));
    }

    @GetMapping("/teacherSelectCourse")
    public CommonResult teacherSelectCourse(BackCourseModel backCourse, PageRequest pageRequest){
        return CommonResult.ok(backCourseService.teacherSelectCourse(backCourse,pageRequest));
    }

    /**
    * @Author 杨友朋
    * @Description TODO 添加课程
    * @Date 2023/8/15 20:59
    * @Return
    * @param
    */
    @PostMapping("/addCourse")
    public CommonResult addCourse(MultipartFile file1, BackCourse backCourse){

        return backCourseService.addCourse(file1,backCourse);
    }

    /**
     * @Author 杨友朋
     * @Description TODO 添加课程
     * @Date 2023/8/15 20:59
     * @Return
     * @param
     */
    @PostMapping("/updateCourse")
    public CommonResult updateCourse(MultipartFile file1, BackCourse backCourse){

        return backCourseService.updateCourse(file1,backCourse);
    }

    /**
    * @Author 杨友朋
    * @Description TODO 根据id单查课程
    * @Date 2023/8/15 20:59
    * @Return
    * @param
    */
    @GetMapping("/selectCourseById")
    public CommonResult selectCourseById(Integer id) {
        return backCourseService.selectCourseById(id);
    }

    /**
     * @Author 杨友朋
     * @Description TODO 更改状态
     * @Date 2023/8/24 9:23
     * @Return
     * @param
     */
    @GetMapping("/upSwitch")
    public CommonResult upSwitch(BackCourse backCourse){
        return backCourseService.upSwitch(backCourse);
    }

    /**
    * @Author 杨友朋
    * @Description TODO 删除课程
    * @Date 2023/8/17 19:36
    * @Return
    * @param
    */
    @GetMapping("/delCourse")
    public CommonResult delCourse(Integer id){
        return backCourseService.delCourse(id);
    }

    /*
    * @Author WX
    * @Description 查询课程数据
    * @Date 2023/8/28 8:44
    * @Return
    * @param null
    */
    @GetMapping("/selectDict")
    public CommonResult queryTeacher() {
        List<SysDictPc> sysDictPcS = backCourseService.selectDict();
        List<SysDictPc> treeData = convertToTree(sysDictPcS);
        return CommonResult.ok(treeData);
    }

    /*
    * @Author WX
    * @Description 将数据以树状形式输出
    * @Date 2023/8/31 10:13
    * @Return
    * @param List<SysDictPc> data
    */
    private List<SysDictPc> convertToTree(List<SysDictPc> data) {
        Map<Integer, SysDictPc> nodes = new HashMap<>();
        List<SysDictPc> tree = new ArrayList<>();

        // 将所有数据构建成以 id 为键的哈希表
        for (SysDictPc item : data) {
            nodes.put(item.getId(), item);
        }

        // 遍历数据构建树状结构
        for (SysDictPc item : data) {
            Integer prentId = item.getPrentId();

            if (prentId == null) {
                // 如果父级id为空，则将该数据作为根节点的一部分，并添加到树的顶层
                tree.add(item);
            } else {
                // 如果父级id不为空，则找到对应的数据节点，将当前节点添加为其子节点
                SysDictPc prentNode = nodes.get(prentId);
                if (prentNode != null) {
                    prentNode.getChildren().add(item);
                }
            }
        }

        return tree;
    }

    /*
    * @Author WX
    * @Description 查询后台管理树状结构 输出级联选择器
    * @Date 2023/8/31 10:15
    * @Return
    * @param id
    */
    @GetMapping("/selectCourseByIdDict")
    public CommonResult selectCourseByIdDict(Integer id) {
        CommonResult result = backCourseService.selectCourseById(id);
        if (result.isFlag()) {
            BackCourseModel data = (BackCourseModel) result.getData();
            Integer subjectId = Integer.valueOf(data.getSubjectId());

            // 创建一个新的 Map 对象，并将属性值存入其中
            Map<String, Object> newData = new HashMap<>();
            newData.put("subjectId", subjectId);
            newData.put("id", data.getId());
            newData.put("courseTitle", data.getCourseTitle());
            newData.put("courseInfo", data.getCourseInfo());
            newData.put("courseImg", data.getCourseImg());
            newData.put("courseStatus", data.getCourseStatus());
            newData.put("teacherId", data.getTeacherId());
            newData.put("payType", data.getPayType());
            newData.put("coursePrice", data.getCoursePrice());
            newData.put("courseClick", data.getCourseClick());
            newData.put("teacherName", data.getTeacherName());
            newData.put("dictName", data.getDictName());
            newData.put("upTime", data.getUpTime());
            // ... 将其他属性值存入 newData

            // 获取父级和子级信息
            String ids = getParentChildIds(subjectId);

            // 更新返回结果的 subjectId 字段为父级和子级的信息
            newData.put("subjectId", ids);

            // 将 newData 设置为结果的 data 属性
            result.setData(newData);
        }
        return result;
    }
    /*
    * @Author WX
    * @Description 获取父级和子级信息
    * @Date 2023/8/31 10:18
    * @Return
    * @param null
    */
    private String getParentChildIds(Integer subjectId) {
        StringBuilder sb = new StringBuilder();
        List<SysDictPc> treeData = backCourseService.selectDict();
        getParentChildIdsRecursive(treeData, subjectId, sb);
        return sb.toString();
    }

    /*
    * @Author WX
    * @Description 遍历父级子级信息
    * @Date 2023/8/31 10:20
    * @Return
    * @param null
    */
    private void getParentChildIdsRecursive(List<SysDictPc> treeData, Integer subjectId, StringBuilder sb) {
        for (SysDictPc node : treeData) {
            if (node.getId().equals(subjectId)) {
                appendParentChildIds(node, sb);
                break;
            } else if (!node.getChildren().isEmpty()) {
                getParentChildIdsRecursive(node.getChildren(), subjectId, sb);
            }
        }
    }

    private void appendParentChildIds(SysDictPc node, StringBuilder sb) {
        if (node.getPrentId() != null) {
            appendParentChildIds(findNodeById(node.getPrentId()), sb);
            sb.append(",").append(node.getId());
        } else {
            sb.append(node.getId());
        }
    }

    private SysDictPc findNodeById(Integer id) {
        List<SysDictPc> treeData = backCourseService.selectDict();
        return findNodeByIdRecursive(treeData, id);
    }

    private SysDictPc findNodeByIdRecursive(List<SysDictPc> treeData, Integer id) {
        for (SysDictPc node : treeData) {
            if (node.getId().equals(id)) {
                return node;
            } else if (!node.getChildren().isEmpty()) {
                SysDictPc result = findNodeByIdRecursive(node.getChildren(), id);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
}
